package com.it.gw.modules.station.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.didi.drouter.utils.TextUtils
import com.it.common.utils.DisplayUtil
import com.it.common.utils.RvSpacesItemUtils
import com.it.data.network.rsp.MyWorkOrderVo
import com.it.gw.R
import com.it.gw.base.BaseActivity
import com.it.gw.databinding.ActivityMyWorkListBinding
import com.it.gw.dialog.ProgressDialog
import com.it.gw.manager.DictionariesManager
import com.it.gw.modules.station.adapter.MyWorkAdapter


//我的工单
class MyWorkOrderActivity : BaseActivity<ActivityMyWorkListBinding>() {

    companion object {
        const val PAGE_SIZE = 20
        const val TAG = "MyWorkOrderActivity"
    }

    private var pageNum = 1
    private val dataList by lazy { mutableListOf<MyWorkOrderVo>() }
    private val myWorkAdapter by lazy {
        MyWorkAdapter(context = this, datas = dataList, listener = {
            val intent = Intent(this, GQOrderStationInfoActivity::class.java)
            intent.putExtra("STCD", it.stcd)
            intent.putExtra("orderDetailId", it.id)
            startActivity(intent)
        })
    }

    override fun initObserver() {

        gqStationViewModel.myWorkOrderVoListLiveData.observe(this) {
            ProgressDialog.hide()
            loadMoreData = false
            binding.swipeRefreshLayout.isRefreshing = false
            if (it.result) {
                if (it.data?.list.isNullOrEmpty())
                {
                    Log.d(TAG, "initObserver: myWorkOrderVoListLiveData ${it.data?.list}")
                    if (pageNum > 1) {
                        pageNum--
                        Toast.makeText(this, "没有更多数据了！", Toast.LENGTH_SHORT).show()
                    } else {
                        //第一次就没数据
                        dataList.clear()
                        myWorkAdapter.notifyDataSetChanged()
//                    llNoData.setVisibility(View.VISIBLE);
//                    srHasData.setVisibility(View.GONE);
                    }

                } else {
//                llNoData.setVisibility(View.GONE);
//                srHasData.setVisibility(View.VISIBLE);
                    if (pageNum == 1) {
                        dataList.clear()
                    }
                    dataList.addAll(it.data!!.list!!)
                    Log.d(TAG, "initObserver: pageGQStationVoListLiveData ${dataList}")
                    myWorkAdapter.notifyDataSetChanged()

                }
            } else {
                Toast.makeText(this, "${it.msg}", Toast.LENGTH_LONG).show()
            }


        }

    }


    @SuppressLint("RestrictedApi")
    override fun initListener() {
        binding.swipeRefreshLayout.setOnRefreshListener {
            clearSeachView()
            pageNum = 1
            getListByUserId()
        }
        binding.rvList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)

                // 获取布局管理器
                val layoutManager = recyclerView.layoutManager as LinearLayoutManager

                // 获取最后一个可见的 item 的位置
                val lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition()

                // 获取总的 item 数量
                val totalItemCount = layoutManager.itemCount
                Log.d(TAG, "onScrolled: lastVisibleItemPosition ${lastVisibleItemPosition} totalItemCount ${totalItemCount} ")
                // 判断是否滑动到了底部
                if (totalItemCount >= PAGE_SIZE && lastVisibleItemPosition == totalItemCount - 1) {
                    // 滑动到了底部，执行相关操作
                    loadMoreData()
                }
            }
        })
        binding.llSearch.rlSearch.setOnClickListener {
            ProgressDialog.show(this)
            pageNum = 1
            getListByUserId()
        }
        //请选择行政区划
        binding.llSearch.addvcd.setOnClickListener {
            showAddvcdWheelPickDialog(okAction = {
                val text2 =
                    if (select2Position >= 0) list2?.get(select2Position)?.text else ""
                val text3 =
                    if (select3Position >= 0) list3?.get(select3Position)?.text else ""



                if (!TextUtils.isEmpty(text2) && !TextUtils.isEmpty(text3)) {
                    binding.llSearch.addvcd.text = "${text2}/${text3}"
                    addvcd = list3?.get(select3Position)?.id
                } else if (!TextUtils.isEmpty(text2)) {
                    binding.llSearch.addvcd.text = "${text2}"
                    addvcd = list2?.get(select2Position)?.id
                } else if (!TextUtils.isEmpty(text3)) {
                    binding.llSearch.addvcd.text = "${text3}"
                    addvcd = list3?.get(select3Position)?.id
                } else {
                    binding.llSearch.addvcd.text = null
                    addvcd = null
                }
            })
        }
        //请选择任务状态
        binding.llSearch.status.setOnClickListener {
            showOrderStatusWheelViewDialog(okAction = { index ->
                binding.llSearch.status.text = orderStatusList?.get(index)?.second
                status = orderStatusList?.get(index)?.first
            })
        }
        //请选择任务类型
        binding.llSearch.orderType.setOnClickListener {
            showOrderTypeWheelViewDialog(okAction = { index ->
                binding.llSearch.orderType.text =
                    DictionariesManager.orderTypeList?.get(index)?.second
                orderType = DictionariesManager.orderTypeList?.get(index)?.first
            })
        }

    }

    var orderType: String? = null
    var status: String? = null

    private var loadMoreData = false;
    private fun loadMoreData() {
        if(loadMoreData){
            return
        }

        Log.d(TAG, "loadMoreData: ")
        pageNum += 1
        loadMoreData = true;
        getListByUserId()
    }

    override fun initData() {


    }

    override fun onResume() {
        super.onResume()
        ProgressDialog.show(this)
        getListByUserId()
    }


    private fun getListByUserId() {
        gqStationViewModel.getListByUserId(
            pageNum,
            PAGE_SIZE,
            addvcd = addvcd,
            status = status,
            orderType = orderType,
            stcd = binding.llSearch.stcd.text.toString(),//搜索条件 测站编码
        )
    }

    override fun initView() {
        setTitle(
            title = R.string.str_my_work_order,
            isBack = true,
            tvRightRes1 = R.string.str_select,
            tvRight1Action = {
                if (binding.llSearch.root.visibility == View.VISIBLE) {
                    binding.llSearch.root.visibility = View.GONE
                    clearSeachView()

                } else {
                    binding.llSearch.root.visibility = View.VISIBLE
                    clearSeachView()
                }

            }
        )

        val map = hashMapOf(RvSpacesItemUtils.BOTTOM_DECORATION to DisplayUtil.dip2px(this, 10f))
        binding.rvList.addItemDecoration(RvSpacesItemUtils(map))
        binding.rvList.adapter = myWorkAdapter


    }

    private fun clearSeachView() {
        addvcd = null
        status = null
        orderType = null
        binding.llSearch.addvcd.text = null
        binding.llSearch.status.text = null
        binding.llSearch.orderType.text = null
        binding.llSearch.stcd.text = null

    }

    override fun setContentView() {
        binding = ActivityMyWorkListBinding.inflate(layoutInflater)
        setContentView(binding.root)
    }
}